package com.wei.myspdemo.service.impl;

import com.wei.myspdemo.entity.User;
import com.wei.myspdemo.repository.UserRepository;
import com.wei.myspdemo.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {
    private  Logger logger=Logger.getLogger(UserServiceImpl.class);
    @Autowired
    UserRepository userRepository;

    @Autowired
    EntityManager entityManager;

    @Override
    public Long authenticate(String userName, String userPassword) {
        logger.debug("query params  username:"+userName+"password:"+userPassword);
        Query query=entityManager.createQuery("select id from User where username=:username and password=:password");
        query.setParameter("username",userName);
        query.setParameter("password",userPassword);
        try {
            List<Long> obj=query.getResultList();
            if(obj!=null&&obj.size()==1){
                Long userId = obj.get(0);
                return userId;
            }else{
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public User findUserByUserNameAndPassword(String userName, String userPassword) {
        Long userId=authenticate(userName,userPassword);
        logger.debug("query databse ,current userId is exists:"+userId);
        if(userId!=null){
            return userRepository.getReferenceById(userId);
        }
        return null;
    }

    public User findUserById(Long userId){
        Optional<User> userList= userRepository.findById(userId);
        return userList.get();
    }


}
